﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using DAO;
using DTO;

namespace ProductManagement
{
    public partial class frmQLThuHoi : Form
    {
        DataTable dtVoPhanPhoi;
        public frmQLThuHoi()
        {
            InitializeComponent();
        }
        private void LoadVoPhanPhoiUngVoiDaiLy()
        {
            int idDaiLy = (int)cboDaiLy.SelectedValue;
            int idGiaoHang = (int)cboDotGiaoHang.SelectedValue;
            String strSql = "select pp.DaiLy, loai.ID as ID, loai.TenLoai as TenLoai, loai.TenLoai &' (' & SoLuong & ')' as TenLoaiSL, SUM(pp.SoLuong) - IIf(Isnull(SUM(tv.SoLuong)),0,sum(tv.SoLuong)) as SoLuong  from (PhanPhoi pp left join LoaiGas loai on pp.LoaiGas=loai.ID) left join ThuHoi tv on (tv.VoPhanPhoi = pp.LoaiGas and tv.DaiLy = pp.DaiLy and tv.MaGiaoHang = pp.MaGiaoHang) where pp.DaiLy = " + idDaiLy + " and pp.MaGiaoHang="+idGiaoHang+" group by loai.ID, loai.TenLoai, pp.DaiLy";
            dtVoPhanPhoi = DataAccess.Query(strSql);
            if (dgvThuHoi.SelectedRows.Count > 0)
                foreach (DataRow row in dtVoPhanPhoi.Rows)
                {
                    if ((int)row["ID"] == (int)dgvThuHoi.SelectedRows[0].Cells["MaVoPhanPhoi"].Value)
                    {
                        row["SoLuong"] = (double)row["SoLuong"] + (int)dgvThuHoi.SelectedRows[0].Cells["SoLuong"].Value;
                    }
                    row["TenLoaiSL"] = row["TenLoai"].ToString() + "(" + row["SoLuong"].ToString() + ")";
                }
            cboVoPhanPhoi.DisplayMember = "TenLoaiSL";
            cboVoPhanPhoi.ValueMember = "ID";
            cboVoPhanPhoi.DataSource = dtVoPhanPhoi;
            
        }
        private void LoadVoThuHoi()
        {
            String strSql = "select * from LoaiGas";
            DataTable dt2 = DataAccess.Query(strSql);
            DataRow newRow = dt2.NewRow();
            newRow["ID"] = 0;
            newRow["TenLoai"] = "Thế chân";
            dt2.Rows.InsertAt(newRow, 0);
            cboVoThuHoi.DisplayMember = "TenLoai";
            cboVoThuHoi.ValueMember = "ID";
            cboVoThuHoi.DataSource = dt2;
        }
        //Chi load nhung dai ly da tung co phan phoi
        private void LoadDaiLy()
        {
            int idGiaoHang = (int)cboDotGiaoHang.SelectedValue;
            String strSql = "select dl.ID as ID, dl.TenDaiLy as TenDaiLy from DaiLy dl inner join PhanPhoi pp on dl.ID = pp.DaiLy where pp.MaGiaoHang="+idGiaoHang;
            DataTable dt = DataAccess.Query(strSql);           
            cboDaiLy.DisplayMember = "TenDaiLy";
            cboDaiLy.ValueMember = "ID";
            cboDaiLy.DataSource = dt;
            if (dt.Rows.Count==0)
                MessageBox.Show("Đợt giao hàng không có phân phối","Thông báo",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            else
                cboDaiLy.SelectedIndex = 0;
        }
        private void LoadDotGiaoHang()
        {
            String strSql = "select* from GiaoHang";
            DataTable dt = DataAccess.Query(strSql);
            cboDotGiaoHang.ValueMember = "ID";
            cboDotGiaoHang.DisplayMember = "Ngay";
            cboDotGiaoHang.DataSource = dt;
        }
        private void frmQLThuHoi_Load(object sender, EventArgs e)
        {
            try
            {
                String strSql = "select th.VoThuVe as MaVoThuHoi, th.VoPhanPhoi as MaVoPhanPhoi, " +
                    "th.ID as ID, dl.ID as MaDaiLy, dl.TenDaiLy as DaiLy, gas1.TenLoai as VoPhanPhoi, " +
                    "gas.TenLoai as VoThuHoi, th.SoLuong as SoLuong, th.PhiDoiVo as PhiDoiVo," +
                    " day(gh.Ngay)&'/'&month(gh.Ngay)&'/'&year(gh.Ngay) as ThoiGian, gh.ID as MaGH from (((ThuHoi th left join LoaiGas gas on th.VoThuVe=gas.ID) left join LoaiGas gas1 on th.VoPhanPhoi=gas1.ID) left join DaiLy dl on th.DaiLy=dl.ID) left join GiaoHang gh on gh.ID=th.MaGiaoHang";
                DataTable dt = DataAccess.Query(strSql);
                dt.Columns.Add("STT");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i]["STT"] = i + 1;
                    if (dt.Rows[i]["MaVoThuHoi"] == System.DBNull.Value)
                        dt.Rows[i]["MaVoThuHoi"] = 0;
                    if (dt.Rows[i]["VoThuHoi"] == System.DBNull.Value)
                        dt.Rows[i]["VoThuHoi"] = "Thế chân";
                }
                BindingSource bs = new BindingSource(dt, null);
                dgvThuHoi.AutoGenerateColumns = false;
                dgvThuHoi.DataSource = bs;
                LoadVoThuHoi();
                
                LoadDotGiaoHang();
            }
            catch (Exception ex) {
                MessageBox.Show("Không thể load form\r\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Close();
            }
        }
        private String KiemTraThuVo()
        {
            String mess = "";
            if (cboDaiLy.SelectedIndex<0 || cboDotGiaoHang.SelectedIndex<0 || cboVoPhanPhoi.SelectedIndex<0 || cboVoThuHoi.SelectedIndex<0
                || txtPhiDoiVo.Text=="" || txtSoLuong.Text == "")
            {
                mess = "Dữ liệu nhập vào chưa đầy đủ.";
                return mess;
            }
            int rs;
            String temp="";
            if (Int32.TryParse(txtPhiDoiVo.Text, out rs)== false)
            {
                temp += "Phí đổi vỏ";
            }           
            if (temp !="")
            {
                mess = "Dữ liệu " + temp + " không đúng"; 
                return mess;
            }
            long soLuong = (long)txtSoLuong.Value;
            foreach (DataRow row in dtVoPhanPhoi.Rows)
            {
                if ((int)row["ID"] == (int)cboVoPhanPhoi.SelectedValue)
                {
                    if (soLuong > (long)((double)row["SoLuong"]))
                    {
                        mess += "Số lượng vượt quá mức cho phép";
                        break;
                    }
                }
            }
            return mess;
        }
        private void btnThem_Click(object sender, EventArgs e)
        {
            ThuVo frm = new ThuVo();
            frm.ShowDialog();
            OnLoad(e);
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            String strError = KiemTraThuVo();
            if (strError != "")
            {
                MessageBox.Show(strError, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ThuHoiDTO thuhoiDTO = new ThuHoiDTO()
            {
                Id = Int32.Parse(txtID.Text),
                DaiLy = (int)cboDaiLy.SelectedValue,
                VoPhanPhoi = (int)cboVoPhanPhoi.SelectedValue,
                VoThuVe = (int)cboVoThuHoi.SelectedValue,
                PhiDoiVo = Int32.Parse(txtPhiDoiVo.Text),
                SoLuong = Int32.Parse(txtSoLuong.Value.ToString()),
                MaGiaoHang = (int)cboDotGiaoHang.SelectedValue
            };
            try
            {
                ThuHoiDAO.UpdateThuHoi(thuhoiDTO);
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                OnLoad(e);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Cập nhật dữ liệu không thành công\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có thật sự muốn xóa không?", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            try
            {
                int id = Int32.Parse(txtID.Text);
                ThuHoiDAO.DeleteThuHoi(id);
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                OnLoad(e);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Cập nhật dữ liệu không thành công\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }

        private void dgvThuHoi_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvThuHoi.SelectedRows.Count > 0)
            {
                txtID.Text = dgvThuHoi.SelectedRows[0].Cells["ID"].Value.ToString();
                cboDotGiaoHang.SelectedValue = (int)dgvThuHoi.SelectedRows[0].Cells["MaGH"].Value;
                LoadDaiLy();
                cboDaiLy.SelectedValue = (int)dgvThuHoi.SelectedRows[0].Cells["MaDaiLy"].Value;
                cboVoThuHoi.SelectedValue = (int)dgvThuHoi.SelectedRows[0].Cells["MaVoThuHoi"].Value;
                LoadVoPhanPhoiUngVoiDaiLy();
                cboVoPhanPhoi.SelectedValue = (int)dgvThuHoi.SelectedRows[0].Cells["MaVoPhanPhoi"].Value;
                txtSoLuong.Value = decimal.Parse(dgvThuHoi.SelectedRows[0].Cells["SoLuong"].Value.ToString());
                txtPhiDoiVo.Text = dgvThuHoi.SelectedRows[0].Cells["PhiDoiVo"].Value.ToString();
                

                //dtpNgay.Value = (DateTime)dgvThuHoi.SelectedRows[0].Cells["Ngay"].Value;
                btnCapNhat.Enabled = true;
                btnXoa.Enabled = true;
            }
            else
            {
                btnCapNhat.Enabled = false;
                btnXoa.Enabled = false;
            }
        }

        private void cboDaiLy_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void cboDaiLy_SelectionChangeCommitted(object sender, EventArgs e)
        {
            LoadVoPhanPhoiUngVoiDaiLy();  
        }

        private void cboDotGiaoHang_SelectionChangeCommitted(object sender, EventArgs e)
        {
            LoadDaiLy();
            LoadVoPhanPhoiUngVoiDaiLy();  
        }

        private void dgvThuHoi_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

       
    }
}
